<?php

namespace App\Services\Platform\Config;

use App\Exceptions\Response\ServiceException;
use App\Models\Game\Config\Currency;
use App\Models\Game\Platform\Org;
use App\Models\Game\Platform\Org\Config;
use App\Services\Service;
use App\Services\Traits\DatabaseMysql;
use App\Models\Game\Config\Game\System;
use App\Models\Game\Config\Game\Platform;

class BettingService extends Service
{
    use DatabaseMysql;

    /**
     * 获取数据列表
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Database\Eloquent\Collection[]|int[]
     */
    public function getList($request)
    {
        $query = Platform::query();

        // 筛选【平台】
        $this->makeWhereParam($request, 'plat_code', $query);
        // 筛选【游戏】
        $this->makeWhereParam($request, 'game_id', $query);

        // 数据条数
        $total = (clone $query)->count();
        // 排序分页
        $this->makeOrderParam($request, $query)->makePaginationParam($request, $query);
        // 查询数据
        $collection = $query->get();

        return [
            $collection,
            $total
        ];
    }

    /**
     * 保存配置
     *
     * @param \Illuminate\Http\Request $request
     */
    public function save($request)
    {
        // 数据 ID
        $id = $request->input('id');
        // 游戏配置
        $config = $request->input('config');
        // 游戏列表
        $gameId = $request->input('game_id');

        $platCode = $request->input('plat_code');

        if (empty($id) && !empty($gameId) && Platform::where(['plat_code' => $platCode,'game_id' => $gameId])->exists()){
            throw new ServiceException(ServiceException::SERVICE_EXISTED_DATA);
        }

        $model = Platform::firstOrNew([
            'plat_code' => $platCode,
            'game_id' => $gameId,
        ], [
            'config' => $config
        ]);
        if ($key = $model->getKey()) {
            // 缓存配置
            $configCache = $model->config;
            // 如果是编辑配置
            if ($key == $id) {
                // 覆盖全部投注配置
                $configCache['globals']['bet'] = $config['globals']['bet'];
                $configCache['globals']['bet_type'] = $config['globals']['bet_type'];
            }
            // 还原配置
            $model->config = $configCache;
        }
//            dd($config);
        $model->save();
//            dd($configCache['globals']);
        // 通知游戏端配置修改
            $model->syncGameService();
    }

    /**
     * 使用默认投注配置覆盖平台投注配置
     *
     * @param string $platCode
     * @param string $gameId
     * @return null | model
     */
    public function fullDefaultBets($platCode, $gameId ,$bet_type)
    {
        $platConfig = Config::where('plat_code', $platCode)->first('currency');
        // 跳过空币种
        if (is_null($platConfig) || empty($currency = $platConfig->currency)) {
            throw new ServiceException(ServiceException::SERVICE_NOT_EXIST_PLAT_CURRENCY);
        }
        // 添加虚拟币
        array_push($currency, '_USD');

        $system = System::where('game_id', $gameId)->first();
        // 跳过空配置
        if (is_null($system) || empty($config = $system->config) || !isset($config['globals']['bet'])) {
            throw new ServiceException(ServiceException::SERVICE_NOT_EXIST_DATA);
        }


        // 过滤币种
        $bets = array_filter($config['globals']['bet'], function ($item) use ($currency) {
            return in_array($item['currency'], $currency);
        });

        $config['globals']['bet_type'] = $config['globals']['bet_type'] ?? 1;
        $config['globals']['bet_status'] = $config['globals']['bet_status'] ?? 0;

        if ($bet_type == 2 && $config['globals']['bet_status'] == 1){
            // 重构数组下标
            $bets = array_values($config['globals']['bet2']);
        }else{
            // 重构数组下标
            $bets = array_values($config['globals']['bet1']);
        }

        // 查询或初始化
        $model = Platform::firstOrNew([
            'plat_code' => $platCode,
            'game_id' => $gameId,
        ], [
            'config' => ['globals' => ['bet' => $bets]]
        ]);

        // 修改配置
        if ($model->getKey()) {
            // 缓存配置
            $configCache = $model->config;
            // 覆盖投注配置
            $configCache['globals']['bet'] = $bets;
            $configCache['globals']['bet_type'] = $bet_type;
            // 还原配置
            $model->config = $configCache;
        }
//        dd($model->config);
        // 保存配置
        $model->save();

        // 通知游戏端配置修改
//        $model->syncGameService();

        return $model;
    }

    /**
     * 使用目标源投注配置覆盖平台投注配置
     *
     * @param string $sourcePlatCode
     * @param array $targetPlatCodes
     * @param array $games
     * @return null
     */
    public function fullSourceBets(string $sourcePlatCode, array $targetPlatCodes, array $games = [])
    {
        $query = Platform::query();
        // 筛选【游戏】
        if (!empty($games)) {
            $query->whereIn('game_id', $games);
        }
        $configModels = $query->where('plat_code', $sourcePlatCode)->get();
        // 数据源配置不存在
        if ($configModels->isEmpty()) {
            throw new ServiceException(ServiceException::SERVICE_NOT_EXIST_DATA);
        }

        $orgModels = Org::whereIn('code', $targetPlatCodes)->get();
        // 目标源不存在
        if ($orgModels->isEmpty()) {
            throw new ServiceException(ServiceException::SERVICE_NOT_EXIST_ORG);
        }

        // 循环复制配置
        $orgModels->each(function ($orgModel) use ($configModels) {
            $configModels->each(function ($configModel) use ($orgModel) {
                $config = $configModel->config;

                if (empty($config['globals'])) {
                    $config['globals'] = new \stdClass();
                }

                $model = Platform::updateOrCreate([
                    'plat_code' => $orgModel->code,
                    'game_id' => $configModel->game_id,
                ], [
                    'config' => $config
                ]);

                // 通知游戏端配置修改
                $model->syncGameService();
            });
        });
    }

    /**
     * 删除配置
     *
     * @param int $id
     */
    public function destroy($id)
    {
        $model = Platform::findOrFail($id);

        $config = $model->config;

        if (isset($config['globals']['bet'])) {
            unset($config['globals']['bet']);
        }
        if (isset($config['globals']['bet2'])) {
            unset($config['globals']['bet2']);
        }
        if (isset($config['globals']['bet1'])) {
            unset($config['globals']['bet1']);
        }
        if (isset($config['globals']['bet_type'])) {
            unset($config['globals']['bet_type']);
        }
        if (isset($config['globals']['line'])) {
            unset($config['globals']['line']);
        }

        if (empty($config['globals'])) {
            $config['globals'] = new \stdClass();
        }

        $model->config = $config;
        $model->save();

        // 通知游戏端配置修改
        $model->syncGameService();
    }

    /**
     * 获取平台币种【真实】
     *
     * @param string $platCode
     * @return array
     * @throws ServiceException
     */
    public function getCurrencyList($platCode)
    {
        $config = Config::where('plat_code', $platCode)->first('currency');

        if (is_null($config) || empty($config->currency)) {
            throw new ServiceException(ServiceException::SERVICE_NOT_EXIST_PLAT_CURRENCY);
        }

        $currencies = Currency::query()
            ->where('type', Currency::TYPE_REAL)
            ->get('currency');

        return $currencies->filter(function ($item) use ($config) {
            return in_array($item->currency, $config->currency);
        });
    }
}
